package com.mk.service;

import act.apidoc.Description;
import act.app.App;
import act.event.OnEvent;
import act.ws.WebSocketCloseEvent;
import act.ws.WebSocketConnectEvent;
import act.ws.WebSocketConnectionManager;
import act.ws.WebSocketContext;
import org.osgl.mvc.annotation.WsAction;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressWarnings("all")
public class WsService {
    private static final AtomicInteger CONN_COUNTER = new AtomicInteger(0);

    @OnEvent
    @Description("socket连接建立时触发的事件")
    public static void handleConnection(WebSocketConnectEvent event) {
        CONN_COUNTER.incrementAndGet();
    }

    @OnEvent
    @Description("任何 websocket 连接断开时候触发的事件")
    public static void handleConnectionClose(WebSocketCloseEvent event) {
        CONN_COUNTER.decrementAndGet();
    }

    @Description("服务端向客户端发送消息")
    public static void handleSendToWeb(String userid, String success) {
        WebSocketConnectionManager connectionManager = App.instance().getInstance(WebSocketConnectionManager.class);
        Map<String, String> map = new HashMap<>();
        map.put("success", success);
        connectionManager.sendJsonToTagged(map, userid);
    }

    @WsAction("/ws/msg")
    @Description("用来将客户端的socket请求注册到tag别名，方便推送")
    public void onMessage(WebSocketContext context) {
        context.tag(context.actionContext().paramVal("userid"));
    }

}
